package com.selfdiscipline.data.repository

import com.selfdiscipline.data.local.dao.TaskDao
import com.selfdiscipline.data.local.entity.TaskEntity
import com.selfdiscipline.data.model.Task
import com.selfdiscipline.data.model.TaskPriority
import com.selfdiscipline.domain.repository.TaskRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import java.time.LocalDateTime
import java.util.Date
import javax.inject.Inject

/**
 * Implementation of the TaskRepository interface
 */
class TaskRepositoryImpl @Inject constructor(
    private val taskDao: TaskDao
) : TaskRepository {
    
    override fun getAllTasks(): Flow<List<TaskEntity>> {
        return taskDao.getAllTasks()
    }
    
    override fun getActiveTasks(): Flow<List<TaskEntity>> {
        return taskDao.getActiveTasks()
    }
    
    override fun getCompletedTasks(): Flow<List<TaskEntity>> {
        return taskDao.getCompletedTasks()
    }
    
    override fun getCompletedTasksInRange(startDate: LocalDateTime, endDate: LocalDateTime): Flow<List<TaskEntity>> {
        return taskDao.getCompletedTasksInRange(startDate, endDate)
    }
    
    override suspend fun getTaskById(id: Long): TaskEntity? {
        return taskDao.getTaskById(id)
    }
    
    override suspend fun insertTask(task: TaskEntity): Long {
        return taskDao.insertTask(task)
    }
    
    override suspend fun updateTask(task: TaskEntity) {
        taskDao.updateTask(task)
    }
    
    override suspend fun deleteTask(id: Long) {
        taskDao.deleteTaskById(id)
    }
    
    override suspend fun completeTask(id: Long, completedAt: LocalDateTime) {
        val task = taskDao.getTaskById(id) ?: return
        val updatedTask = task.copy(
            isCompleted = true,
            completedAt = completedAt
        )
        taskDao.updateTask(updatedTask)
    }
    
    override fun getPendingTasks(): Flow<List<Task>> {
        return taskDao.getActiveTasks().map { taskEntities ->
            taskEntities.map { entity ->
                Task(
                    id = entity.id.toString(),
                    title = entity.title,
                    description = entity.description,
                    deadline = entity.dueDate?.let { Date.from(it.atZone(java.time.ZoneId.systemDefault()).toInstant()) },
                    priority = when(entity.priority) {
                        2 -> TaskPriority.HIGH
                        0 -> TaskPriority.LOW
                        else -> TaskPriority.MEDIUM
                    },
                    completed = entity.isCompleted,
                    completedAt = entity.completedAt?.let { Date.from(it.atZone(java.time.ZoneId.systemDefault()).toInstant()) }
                )
            }
        }
    }
} 